package com.fulihui.wgj.admin.api.user;

import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.error.Errors;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.JedisUtil;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.wgj.admin.api.base.BaseController;
import com.fulihui.wgj.admin.api.user.request.ModifyPwdReq;
import com.fulihui.wgj.admin.api.user.request.UserLoginReq;
import com.fulihui.wgj.admin.api.user.request.UserRegisterReq;
import com.fulihui.wgj.admin.config.properties.JwtProperties;
import com.fulihui.wgj.admin.integration.UserLoginClient;
import com.fulihui.wgj.admin.security.jwt.JwtHelper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.Objects;

import static com.fulihui.common.constants.JwtConstants.ACCESS_JWT_TOKEN;
import static com.fulihui.common.constants.JwtConstants.BEARER;
import static com.fulihui.common.error.Errors.UserLoginError.CONFIRM_PASSWORD_FAILED;

/**
 * 用户登录
 *
 * @author: Levon
 * @version: v 0.1 2018-06-14 09:32
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController extends BaseController {

    @Autowired
    private UserLoginClient userLoginServiceClient;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JedisUtil jedisUtil;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation("用户登录")
    public Result<Boolean> login(@RequestBody @Valid UserLoginReq request, BindingResult validResult, HttpServletResponse servletResponse) {

        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }

        BaseResult baseResult = userLoginServiceClient.login(request.getLoginId(), request.getPassword());

        //登录成功，生成凭据
        if (RpcResultCheckUtil.isSuccess(baseResult)) {


            String jwtToken = JwtHelper.createJWT(request.getLoginId(), null);

            //把凭据放入header中
            servletResponse.setHeader(ACCESS_JWT_TOKEN, jwtToken);
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation("用户注册")
    public Result<Boolean> register(@RequestBody @Valid UserRegisterReq request, BindingResult validResult) {

        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }

        //确认密码
        if (!StringUtils.equals(request.getPassword(), request.getConfirmPassword())) {
            return JsonResultBuilder.fail(CONFIRM_PASSWORD_FAILED.getErrcode(), CONFIRM_PASSWORD_FAILED.getErrmsg());
        }

        BaseResult baseResult = userLoginServiceClient.register(request.getLoginId(), request.getPassword());

        //注册成功
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @PostMapping(value = "/password")
    @ApiOperation("修改密码")
    public Result<Boolean> modifyPwd(@RequestBody @Valid ModifyPwdReq request, BindingResult validResult) {

        Result valid = valid(validResult);
        if (Objects.nonNull(valid)) {
            return valid;
        }

        BaseResult baseResult = userLoginServiceClient.updatePassword(request.getLoginId(), request.getPassword(), request.getOldPassword());
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ApiOperation("注销登录")
    public Result<Boolean> logout(HttpServletRequest servletRequest, HttpServletResponse response) {

        String loginId = getLoginId();
        //把token加入黑名单，拦截器处理如果在黑名单中的token强制无效
        String authHeader = servletRequest.getHeader(ACCESS_JWT_TOKEN);
        if (authHeader == null || !authHeader.startsWith(BEARER)) {
            return JsonResultBuilder.fail(Errors.Commons.SYSTEM_ERROR.getErrcode(), "token非法");
        }

        String token = authHeader.substring(7);
        Claims claims = JwtHelper.parseJWT(token, jwtProperties.getBase64Secret());
        if (claims == null) {
            return JsonResultBuilder.succ(true);
        }

        Date expiration = claims.getExpiration();

        //保存到redis
        jedisUtil.set(token, loginId, expiration.getDate() / 1000);
        return JsonResultBuilder.succ(true);
    }
}
